

task default: [
  :copy, 
  'man:all'
]

task :copy do
  Dir['**/*'].reject{|fn|
    fn == 'Rakefile' or fn.pathmap('%x') == '.gemspec'
  }.each do |filename|

    # Skip directories
    file = Pathname.new filename
    next unless file.file?

    # Ignore manpage models
    next if filename.pathmap('%x') == '.ronn'

    # Copy
    mkdir_p filename.pathmap "#{PARAMS[:next_step_dir]}/%d"
    cp filename, "#{PARAMS[:next_step_dir]}/#{filename.pathmap('%p')}"
  end
end

namespace :man do

  task :man do
    mkdir_p "#{PARAMS[:next_step_dir]}/man"
  end

  desc 'generate man pages'
  task all: [:man] do
    Dir['man/*.ronn'].each do |manpage_model|
      # Manual name
      name = PARAMS[:gemspec].name
      version = PARAMS[:gemspec].version.split('.')[0..1].join '.'
      manual = "#{name} v#{version} manual"

      # Output file
      outfile = "#{PARAMS[:next_step_dir]}/#{manpage_model.pathmap('%X')}"

      # Generate
      sh "ronn --pipe --manual '#{manual}' -s toc --roff '#{manpage_model}' > '#{outfile}'"
    end
  end

=begin
  namespace :git do

    desc 'add the man pages to git'
    task :add do
      sh "git add man"
    end

    desc 'add and commit the man pages to git'
    task all: [:add]

  end

  desc 'build the man pages, then add and commit them to git'
  task all: [:build, 'git:all']
=end

end


# Task parameters ##################################
PARAMS = {
  next_step_dir: Dir['../3.*'].first,
  gemspec:       nil
}

# Capture the gem specification by 'evaluating the *.gemspec file
# using a fake OpenStruct object that passes for a
# Gem::Specification instance.
begin
  require 'ostruct'
  require 'pathname'

  module Gem
    # Fake Gem::Specification class
    class Specification
      def initialize 
        @spec = OpenStruct.new
        @spec.executables = []
        @spec.metadata = {}
        @spec.development_dependencies = []
        @spec.singleton_class.class_eval do
          def add_development_dependency *geminfo
            self.development_dependencies << geminfo
          end
        end

        yield @spec
        ::PARAMS[:gemspec] = @spec
      end
    end
  end

  def read_gemspec
    gemspec = Dir['../*/*.gemspec'].first
    return unless gemspec
    gemspec = Pathname.new(gemspec)
    return unless gemspec.file?
    gemspec = gemspec.read
    self.instance_eval gemspec
  end

  read_gemspec
end

